using SG3L_RAG.Application.Interfaces;

namespace SG3L_RAG.Application.Services
{
    public class MockAIService : IAIService
    {
        private readonly Random _random = new();

        public MockAIService()
        {
        }

        public async Task<string> GenerateAnswerAsync(string question, List<string> contexts)
        {
            try
            {
                // 模拟AI处理时间
                await Task.Delay(1000 + _random.Next(2000));

                if (!contexts.Any())
                {
                    return "抱歉，我没有找到相关的文档信息来回答您的问题。请尝试用不同的方式提问或上传相关文档。";
                }

                // 基于上下文生成回答
                var contextText = string.Join("\n\n", contexts.Take(3)); // 只使用前3个最相关的上下文
                
                var answer = GenerateContextBasedAnswer(question, contextText);
                
                return answer;
            }
            catch (Exception)
            {
                return "抱歉，在处理您的问题时发生了错误，请稍后重试。";
            }
        }

        public async Task<float[]> GenerateEmbeddingAsync(string text)
        {
            try
            {
                // 模拟向量生成时间
                await Task.Delay(200 + _random.Next(300));

                // 生成模拟的嵌入向量（1536维，模拟OpenAI的text-embedding-ada-002）
                var embedding = new float[1536];
                var textHash = text.GetHashCode();
                var seed = Math.Abs(textHash);
                var random = new Random(seed);

                // 基于文本内容生成确定性的向量
                for (int i = 0; i < embedding.Length; i++)
                {
                    embedding[i] = (float)(random.NextGaussian() * 0.1);
                }

                // 归一化向量
                var norm = Math.Sqrt(embedding.Sum(x => x * x));
                for (int i = 0; i < embedding.Length; i++)
                {
                    embedding[i] = (float)(embedding[i] / norm);
                }

                return embedding;
            }
            catch (Exception)
            {
                return new float[1536]; // 返回零向量
            }
        }

        public async Task<string> SummarizeDocumentAsync(string content)
        {
            try
            {
                // 模拟处理时间
                await Task.Delay(500 + _random.Next(1000));

                if (string.IsNullOrWhiteSpace(content))
                {
                    return "文档内容为空。";
                }

                // 简单的摘要生成逻辑
                var sentences = content.Split(new[] { '.', '。', '!', '！', '?', '？' }, StringSplitOptions.RemoveEmptyEntries);
                var importantSentences = sentences
                    .Where(s => s.Trim().Length > 20) // 过滤太短的句子
                    .Take(3) // 取前3句
                    .Select(s => s.Trim())
                    .ToList();

                var summary = string.Join(" ", importantSentences);
                if (summary.Length > 300)
                {
                    summary = summary.Substring(0, 297) + "...";
                }

                return summary;
            }
            catch (Exception)
            {
                return "摘要生成失败。";
            }
        }

        public async Task<List<string>> ExtractKeywordsAsync(string text)
        {
            try
            {
                // 模拟处理时间
                await Task.Delay(300 + _random.Next(500));

                if (string.IsNullOrWhiteSpace(text))
                {
                    return new List<string>();
                }

                // 简单的关键词提取逻辑
                var words = text.Split(new[] { ' ', '\n', '\r', '\t', '，', '。', '！', '？', '；', '：' }, 
                    StringSplitOptions.RemoveEmptyEntries);

                var keywords = words
                    .Where(w => w.Length >= 2 && w.Length <= 15) // 过滤长度
                    .GroupBy(w => w.ToLower())
                    .Where(g => g.Count() > 1) // 出现次数超过1次
                    .OrderByDescending(g => g.Count())
                    .Take(10)
                    .Select(g => g.Key)
                    .ToList();

                return keywords;
            }
            catch (Exception)
            {
                return new List<string>();
            }
        }

        private string GenerateContextBasedAnswer(string question, string context)
        {
            // 基于问题类型生成不同的回答模板
            var lowerQuestion = question.ToLower();
            
            if (lowerQuestion.Contains("是什么") || lowerQuestion.Contains("什么是"))
            {
                return $"根据相关文档，{ExtractDefinition(context, question)}。\n\n以下是相关的详细信息：\n{TruncateContext(context, 300)}";
            }
            else if (lowerQuestion.Contains("如何") || lowerQuestion.Contains("怎么"))
            {
                return $"根据文档内容，关于您问的\"{question}\"，建议的方法如下：\n\n{ExtractSteps(context)}\n\n更多详细信息请参考相关文档。";
            }
            else if (lowerQuestion.Contains("为什么"))
            {
                return $"关于您提出的问题，根据相关文档分析：\n\n{ExtractReasons(context)}\n\n这是基于当前可用文档的分析结果。";
            }
            else
            {
                return $"根据相关文档内容，针对您的问题\"{question}\"，我为您整理了以下信息：\n\n{TruncateContext(context, 400)}\n\n希望这些信息对您有帮助。如需了解更多详情，请查看完整文档。";
            }
        }

        private string ExtractDefinition(string context, string question)
        {
            // 简单的定义提取逻辑
            var sentences = context.Split(new[] { '.', '。' }, StringSplitOptions.RemoveEmptyEntries);
            var definitionSentence = sentences.FirstOrDefault(s => s.Contains("是") || s.Contains("指") || s.Contains("为"));
            return definitionSentence?.Trim() ?? TruncateContext(context, 100);
        }

        private string ExtractSteps(string context)
        {
            // 简单的步骤提取逻辑
            var sentences = context.Split(new[] { '.', '。', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var steps = sentences
                .Where(s => s.Contains("步骤") || s.Contains("首先") || s.Contains("然后") || s.Contains("最后") || s.Contains("第"))
                .Take(5)
                .Select((s, i) => $"{i + 1}. {s.Trim()}")
                .ToList();

            return steps.Any() ? string.Join("\n", steps) : TruncateContext(context, 300);
        }

        private string ExtractReasons(string context)
        {
            // 简单的原因提取逻辑
            var sentences = context.Split(new[] { '.', '。' }, StringSplitOptions.RemoveEmptyEntries);
            var reasons = sentences
                .Where(s => s.Contains("因为") || s.Contains("由于") || s.Contains("原因") || s.Contains("导致"))
                .Take(3)
                .Select(s => s.Trim())
                .ToList();

            return reasons.Any() ? string.Join("\n", reasons) : TruncateContext(context, 300);
        }

        private string TruncateContext(string context, int maxLength)
        {
            if (string.IsNullOrEmpty(context)) return "";
            if (context.Length <= maxLength) return context;
            
            var truncated = context.Substring(0, maxLength);
            var lastSpace = truncated.LastIndexOf(' ');
            return (lastSpace > 0 ? truncated.Substring(0, lastSpace) : truncated) + "...";
        }
    }

    // 扩展方法：生成高斯分布随机数
    public static class RandomExtensions
    {
        public static double NextGaussian(this Random random, double mean = 0, double stdDev = 1)
        {
            // Box-Muller变换
            double u1 = 1.0 - random.NextDouble();
            double u2 = 1.0 - random.NextDouble();
            double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
            return mean + stdDev * randStdNormal;
        }
    }
}
